from datetime import datetime

from sqlalchemy import *
from sqlalchemy.ext.activemapper import ActiveMapper, column, \
                                    one_to_many, one_to_one, many_to_many

from turbogears import identity 
from turbogears.database import metadata, session

import dispatch

import time
import postmarkup

class Page(ActiveMapper):
    class mapping:
        page_id = column(Integer, primary_key=True)
        blog_id = column(Integer, foreign_key=ForeignKey('blog.blog_id'))
        path = column(String(255))
        title = column(Unicode(255))
        content = column(Unicode())
        content_format = column(Unicode(25), default = "html")
        date_created = column(DateTime, default=datetime.now)
        date_modified = column(DateTime, default=datetime.now)

    @dispatch.generic()
    def getContentHtml(self):
        pass
    
    @getContentHtml.when('self.content_format == "html"')
    def getContentHtmlfromHtml(self):
        return self.content

    @getContentHtml.when('self.content_format == "postmarkup"')
    def getContentHtmlPostMarkup(self):
        """ 
        Describe how to convert the entire comment content into HTML.
        """
        return pm.render_to_html(self.content)

    @getContentHtml.when('self.content_format == "kiwi"')
    def getContentHtmlKiwi(self):
        from StringIO import StringIO
        from kiwi.main import run
        return run(arguments=['--body-only', '--level=1'], input=StringIO(self.content), noOutput=True)[1]

class CodeTag(postmarkup.TagBase):
    """ 
    Generates a code block that is syntax highlighted.
    """
    def __init__(self):
        postmarkup.TagBase.__init__(self, 'code')
    
    def open(self, open_pos):
        return '<pre class="prettify">'

    def close(self, close_pos, content):
        return "</pre>" 

# Build the postmarkup renderer for comments.
pm = postmarkup.create(use_pygments=False)
pm.add_tag('code', CodeTag)
pm.add_tag(u'h1', postmarkup.SimpleTag, u'h1', u'h1')
pm.add_tag(u'h2', postmarkup.SimpleTag, u'h2', u'h2')
pm.add_tag(u'h3', postmarkup.SimpleTag, u'h3', u'h3')
pm.add_tag(u'h4', postmarkup.SimpleTag, u'h4', u'h4')
pm.add_tag(u'h5', postmarkup.SimpleTag, u'h5', u'h5')
